import * as echarts from 'echarts'
import {addMyAttention as addMyAttentionToDefault} from '@/api/eye/myAttention'
import {Notification} from 'element-ui'

/**
 * 根据基金code生成一条折线图,多条则循环调用
 * @param divId div的id值
 * @param title k线图的标题
 * @param rawData k线图数据
 * @param renderType 渲染k线图的类型,默认不传值动态生成div,值为1则在vue模板页面创建div
 */
export function renderKLine(divId, title, rawData, renderType) {

  if (renderType === undefined) {
    //顶层topDiv
    let topDiv = document.getElementById('topDiv')

    let chartDiv = document.createElement('div')
    chartDiv.id = divId
    chartDiv.style.width = '100%'
    chartDiv.style.height = '500px'
    topDiv.appendChild(chartDiv)
  }

  // 基于准备好的dom，初始化echarts实例
  let myChart = echarts.init(document.getElementById(divId))

  function calculateMA(dayCount, data) {
    let result = []
    for (let i = 0, len = data.length; i < len; i++) {
      if (i < dayCount) {
        result.push('-')
        continue
      }
      let sum = 0
      for (let j = 0; j < dayCount; j++) {
        sum += +data[i - j][1]
      }
      result.push((sum / dayCount).toFixed(2))
    }
    return result
  }

  // 日期格式['2015/12/30', '2015/12/31']
  let dates = rawData.date

  // 设置K线图展示的开始位置
  let start
  if (dates.length < 360) {
    start = 0
  } else if (dates.length < 720) {
    start = 20
  } else {
    start = 80
  }

  // 价格格式开盘，收盘，最低，最高[[3570.47,3539.18,2000.35,3580.6],[3566.73,4000.88,2000.11,5000.68]]
  let priceData = rawData.price
  if (priceData.length >= 2) {
    let tmpData = []
    tmpData.push([priceData[0][0], priceData[0][1], priceData[0][2], priceData[0][3], '-', '-'])
    for (let i = 1; i < priceData.length; i++) {
      let p = []
      p.push(priceData[i][0])
      p.push(priceData[i][1])
      p.push(priceData[i][2])
      p.push(priceData[i][3])
      // 收盘价涨幅
      p.push(((priceData[i][1] - priceData[i - 1][1]) * 100 / priceData[i - 1][1]).toFixed(2))
      // 最高价和最低价的幅度
      p.push(((priceData[i][3] - priceData[i][2]) * 100 / priceData[i][2]).toFixed(2))
      tmpData.push(p)
    }
    priceData = tmpData
  }
  // 指定图表的配置项和数据
  let option = {
    title: {
      triggerEvent: true,
      backgroundColor: '#ff4949',
      right: '0',
      text: title
    },
    legend: {
      data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30', 'MA60', 'MA125', 'MA250'],
      inactiveColor: '#777'
    },
    grid: {
      left: '30',
      right: '10',
      bottom: 80
    },
    tooltip: {
      trigger: 'axis',
      borderColor: 'red',
      borderWidth: 2,
      textStyle: {
        color: 'red',
        fontWeight: 'bolder',
        fontSize: 16
      },
      backgroundColor: 'white',
      axisPointer: {
        animation: false,
        type: 'cross',
        lineStyle: {
          color: 'blue',
          width: 2,
          opacity: 1
        }
      },
      formatter: function (params) {
        //params[0]开盘收盘最低最高价,params[1]五日线数据
        let p = params[0]
        let data = p.data
        let r = '<span style="color: #409EFF">' + p.name + '</span><br>' +
          '开盘:&nbsp;' + data[1] + '<br>' +
          '收盘:&nbsp;' + data[2] + '<br>' +
          '最低:&nbsp;' + data[3] + '<br>' +
          '最高:&nbsp;' + data[4] + '<br>' +
          '<span style="color: #409EFF">涨跌:&nbsp;' + data[5] + '%' + '</span><br>' +
          '幅度' + data[6] + '%' + '<br>' +
          'MA5:&nbsp;' + params[1].data + '<br>'
        if (params.length > 3) {
          r = r + 'MA10:&nbsp;' + params[2].data + '<br>' +
            'MA20:&nbsp;' + params[3].data
        }
        return r
      }
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLine: {lineStyle: {color: '#8392A5'}}
    },
    yAxis: {
      scale: true,
      axisLine: {lineStyle: {color: 'red'}},
      splitLine: {show: true}
    },
    dataZoom: [
      {
        textStyle: {
          color: 'red'
        },
        selectedDataBackground: {
          areaStyle: {
            color: 'blue'
          },
          lineStyle: {
            opacity: 2,
            width: 2,
            color: 'blue'
          }
        },
        dataBackground: {
          areaStyle: {
            color: 'red'
          },
          lineStyle: {
            opacity: 0.8,
            width: 2,
            color: 'yellow'
          }
        },
        brushSelect: true,
        start: start,
        end: 100
      },
      {
        type: 'inside'
        // zoomOnMouseWheel: 'ctrl'
      }
    ],
    series: [
      {
        type: 'candlestick',
        name: 'Day',
        data: priceData,
        itemStyle: {
          color: '#FD1050',
          color0: '#0CF49B',
          borderColor: '#FD1050',
          borderColor0: '#0CF49B'
        }
      },
      {
        name: 'MA5',
        type: 'line',
        color: 'black',
        data: calculateMA(5, priceData),
        smooth: true,
        showSymbol: false,
        lineStyle: {
          width: 1
        }
      },
      {
        name: 'MA10',
        type: 'line',
        color: '#dba536',
        data: calculateMA(10, priceData),
        smooth: true,
        showSymbol: false,
        lineStyle: {
          width: 1
        }
      },
      {
        name: 'MA20',
        type: 'line',
        color: '#df7e84',
        data: calculateMA(20, priceData),
        smooth: true,
        showSymbol: false,
        lineStyle: {
          width: 1
        }
      },
      {
        name: 'MA30',
        type: 'line',
        color: '#85bd72',
        data: calculateMA(30, priceData),
        smooth: true,
        showSymbol: false,
        lineStyle: {
          width: 1
        }
      },
      {
        name: 'MA60',
        type: 'line',
        color: '#437798',
        data: calculateMA(60, priceData),
        smooth: true,
        showSymbol: false,
        lineStyle: {
          width: 1
        }
      },
      {
        name: 'MA125',
        type: 'line',
        color: '#975e95',
        data: calculateMA(125, priceData),
        smooth: true,
        showSymbol: false,
        lineStyle: {
          width: 1
        }
      },
      {
        name: 'MA250',
        type: 'line',
        color: '#a15756',
        data: calculateMA(250, priceData),
        smooth: true,
        showSymbol: false,
        lineStyle: {
          width: 1
        }
      }
    ]
  }

  // 使用指定的配置项和数据显示图表。
  myChart.setOption(option)
  myChart.on('click', function (p) {
    let code = p.event.target.style.text.split('_')[0]
    Notification.success({
      title: '成功添加[' + code + ']到我的默认关注',
      duration: 2000
    })
    addMyAttentionToDefault({stockCode: code, groupId: '1'}).then(() => {
      console.log('已加入默认分组!')
    })
  })
}
